package com.iteaj.iot.client.component;

import cn.hutool.core.util.StrUtil;
import com.iteaj.iot.ConcurrentStorageManager;
import com.iteaj.iot.client.ClientComponent;
import com.iteaj.iot.client.ClientConnectProperties;
import com.iteaj.iot.client.IotClient;
import com.iteaj.iot.client.MultiClientManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 默认的客户端管理实现
 */
public class SimpleMultiClientManager extends ConcurrentStorageManager<String, IotClient> implements MultiClientManager {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public synchronized void addClient(Object clientKey, IotClient value) {
        String clientKeyStr = clientKey.toString();
        if(StrUtil.isBlank(clientKeyStr)) {
            throw new IllegalArgumentException("参数[clientKey]不能为空");
        }

        if(!isExists(clientKeyStr)) {
            add(clientKeyStr, value);
        } else {
            if(logger.isDebugEnabled()) {
                logger.warn("客户端管理({}) 客户端已存在 - 客户端标识：{} - 当前数量：{}"
                        , value.getClientComponent().getName(), clientKeyStr, size());
            }
        }
    }

    @Override
    public IotClient getClient(Object clientKey) {
        return get(clientKey.toString());
    }

    @Override
    public IotClient removeClient(Object clientKey) {
        return remove(clientKey.toString());
    }

    @Override
    public List<IotClient> clients() {
        return Collections.unmodifiableList(getStorage().values()
                .stream()
                .collect(Collectors.toList()));
    }

}
